<?php

namespace App\Http\Controllers;

use App\Models\Column;
use App\Models\Article;

class ArticleController extends Controller
{
    //
    public function index()
    {
        $column = Column::where('parent_id',0)->where('type',1)->get();
        $articles   = Article::where(['state'=>1])->select('id','title','created_at','updated_at')->orderBy('created_at','desc')->orderBy('views','desc')->take(10)->get();
        return view('article.index',compact('column','articles'));
    }

    public function listId($id)
    {
        $art_col    = Column::where('id',$id)->where('type',1)->first();
        if(!$art_col){
            return redirect('article', 301);
        }
        $column     = Column::where('parent_id',0)->where('type',1)->get();
        $articles   = Article::where(['state'=>1,'column_id'=>$id])->select('id','title','created_at','updated_at')->orderBy('created_at','desc')->paginate(10);
        return view('article.list',compact('column','id','articles','art_col'));
    }
    public function show($id)
    {
        $article   = Article::where(['id'=>$id])->first();
        if(!$article){
            return redirect('article', 301);
        }
        Article::where('id', $id)->increment('views');
        $art_col    = Column::where('id',$article->column_id)->where('type',1)->first();
        $prev = $this->getPrevArticleId($id, $article->column_id);
        $next = $this->getNextArticleId($id, $article->column_id);
        $article_list = Article::where(['state'=>'1','column_id'=>$article->column_id])->orderBy('views','desc')->take(10)->get();
        return view('article.show',compact('art_col','article','prev','next','article_list'));
    }
    /**
     * 上一个
     */
    protected function getPrevArticleId($id, $cate_id){
        $aid = Article::where('id', '<', $id)->where('state',1)->where('column_id',$cate_id)->max('id');
        return Article::where('id','=',$aid)->first();
    }
    /**
     * 下一个
     */
    protected function getNextArticleId($id,$cate_id) {
        $aid = Article::where('id', '>', $id)->where('state',1)->where('column_id',$cate_id)->min('id');
        return Article::where('id','=',$aid)->first();
    }
}
